package com.atguigu.gulimall.product.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryDao> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都有默认值的
        treeNodeConfig.setWeightKey("sort");
        treeNodeConfig.setIdKey("catId");
        // 最大递归深度
        treeNodeConfig.setDeep(3);

        //转换器 (含义:找出父节点为字符串零的所有子节点, 并递归查找对应的子节点, 深度最多为 3)
        List<Tree<String>> categoryTreeNodes = TreeUtil.build(categoryEntities, "0", treeNodeConfig,
                (category, tree) -> {
                    tree.setId(category.getCatId().toString());
                    tree.setParentId(category.getParentCid().toString());
                    tree.setWeight(category.getSort()==null?0:category.getSort());
                    tree.setName(category.getName());
                    // 扩展属性 ...
                    tree.putExtra("catLevel", category.getCatLevel());
                    tree.putExtra("showStatus", category.getShowStatus());
                    tree.putExtra("icon", category.getIcon());
                    tree.putExtra("productUnit", category.getProductUnit());
                    tree.putExtra("productCount", category.getProductCount());
                });
        // TODO 测试3级分类列表
        return null;
    }

}